
import Vue from 'vue'

const state = {
  formDataList: [],
  activeFormData: Object.create(null),
  status: 'edit',
  pageName: '未命名',
  path: ''
}

const getters = {
  activeId: state => {
    state.activeId = state?.activeFormData?.formId || null
    return state?.activeFormData?.formId || null
  }
}

const mutations = {
  SETACTIVE: (state, data) => {
    const activeId = data.formId
    state.activeFormData = state.formDataList.find(item => item.formId === activeId)
    // state.activeFormData = Object.assign({}, value)
  },
  SETFORMDATA: (state, value) => {
    state.formDataList = Object.assign([], value)
  },
  DEL: (state, value) => {
    const filterData = state.formDataList.filter(item => item.formId !== value)
    state.formDataList = filterData
    setTimeout(() => {
      const firstData = state.formDataList?.length > 0 ? state.formDataList[0] : {}
      state.activeFormData = JSON.parse(JSON.stringify(firstData))
    })
  },
  ADDFORM(state, data) {
    state.formDataList.push(data)
    state.activeFormData = data
  },
  // 设置属性值
  SETPROP(state, data) {
    const { value, key } = data
    // 设置的是否是style
    if (key.includes('style')) {
      const curKey = key.split('.')[1]
      state.activeFormData.style[curKey] = JSON.parse(JSON.stringify(value))
    } else if (key.includes('operatStyle')) {
      const curOperatKey = key.split('.')[1]
      state.activeFormData.operatStyle[curOperatKey] = JSON.parse(JSON.stringify(value))
    } else {
      state.activeFormData[key] = JSON.parse(JSON.stringify(value))
    }

  },
  DELOPTION(state, index) {
    state.activeFormData?.options.splice(index, 1)
  },
  // 添加下拉选项
  ADDOPTION(state) {
    state.activeFormData.options.push({
      label: '',
      value: ''
    })
  },
  // 删除正则校验
  DELREGULAR(state, index) {
    state.activeFormData.regList.splice(index, 1)
  },
  // 删除函数校验
  DELFN(state, index) {
    state.activeFormData.fnList.splice(index, 1)
  },
  // 添加校验,包含正则(regular)和函数(fn)
  ADDVERFIGY(state, type) {
    if (Object.keys(state.activeFormData).length !== 0) {
      // 正则
      if (type === 'regular') {
        state.activeFormData.regList.push({
          reg: '',
          msg: ''
        })
      } else {
        state.activeFormData.fnList.push('')
      }
    }
  },
  // 清空数据
  CLEARDATA(state) {
    // state.activeFormData = {}
  },
  // vModel不是字符串时设置
  SETVMODEL(state, data) {
    const { value, formId } = data
    state.formDataList.forEach(item => {
      if (item.formId === formId) {
        item.vModel = value
      }
    })
  },
  // 保存页面
  SAVEPAGE(state, data) {
    const { pageName, path } = data
    state.pageName = pageName
    state.path = path
  }
}

const actions = {

}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}